package util;

import java.io.File;


import javax.xml.parsers.*;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;




public class MyXMLParser {
 
	public static void main(String[] args) throws Exception {
		MyXMLParser xmlParser=new MyXMLParser();
		Document doc = xmlParser.getDocument(args[0]);
		Element root=doc.getDocumentElement();
		xmlParser.findNode(root, args[1]);
	}
	
	public DocumentBuilder getBuilder() throws ParserConfigurationException {
		DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance();
		return factory.newDocumentBuilder();
		
	}
	public Document getDocument(String file) throws Exception{
		DocumentBuilder builder = getBuilder();
		return builder.parse(new File(file));
	}
	
	public void findNode(Node node,String nodeValue){
		if(node.getNodeValue() !=null && node.getNodeValue().equalsIgnoreCase(nodeValue)){
			System.out.print("The path is:");
			printPath(node.getParentNode());
		}
		else if(node == null);
		else{
			NodeList list =node.getChildNodes();
			for(int i=0;i<list.getLength();i++){
				Node aNode=list.item(i);
				findNode(aNode, nodeValue);
			}
					
		}
	}

	private void printPath(Node node) {
		if(node.getParentNode().getNodeType() == Node.DOCUMENT_NODE  )
			System.out.print(node.getNodeName());
		else if( node.getNodeType() == Node.ELEMENT_NODE){
			printPath(node.getParentNode());
			System.out.print("->"+node.getNodeName());
		}
	}
}
